{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ce571de3",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# 数据操作\n",
    ":label:`sec_ndarray`\n",
    "\n",
    "为了能够完成各种数据操作，我们需要某种方法来存储和操作数据。\n",
    "通常，我们需要做两件重要的事：（1）获取数据；（2）将数据读入计算机后对其进行处理。\n",
    "如果没有某种方法来存储数据，那么获取数据是没有意义的。\n",
    "\n",
    "首先，我们介绍$n$维数组，也称为*张量*（tensor）。\n",
    "使用过Python中NumPy计算包的读者会对本部分很熟悉。\n",
    "无论使用哪个深度学习框架，它的*张量类*（在MXNet中为`ndarray`，\n",
    "在PyTorch和TensorFlow中为`Tensor`）都与Numpy的`ndarray`类似。\n",
    "但深度学习框架又比Numpy的`ndarray`多一些重要功能：\n",
    "首先，GPU很好地支持加速计算，而NumPy仅支持CPU计算；\n",
    "其次，张量类支持自动微分。\n",
    "这些功能使得张量类更适合深度学习。\n",
    "如果没有特殊说明，本书中所说的张量均指的是张量类的实例。\n",
    "\n",
    "## 入门\n",
    "\n",
    "本节的目标是帮助读者了解并运行一些在阅读本书的过程中会用到的基本数值计算工具。\n",
    "如果你很难理解一些数学概念或库函数，请不要担心。\n",
    "后面的章节将通过一些实际的例子来回顾这些内容。\n",
    "如果你已经具有相关经验，想要深入学习数学内容，可以跳过本节。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2e061c6",
   "metadata": {
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "(**首先，我们导入`torch`。请注意，虽然它被称为PyTorch，但是代码中使用`torch`而不是`pytorch`。**)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c576bdce",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:00.300201Z",
     "iopub.status.busy": "2022-12-07T16:28:00.299529Z",
     "iopub.status.idle": "2022-12-07T16:28:01.537384Z",
     "shell.execute_reply": "2022-12-07T16:28:01.536531Z"
    },
    "origin_pos": 5,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ad4854b",
   "metadata": {
    "origin_pos": 8
   },
   "source": [
    "[**张量表示一个由数值组成的数组，这个数组可能有多个维度**]。\n",
    "具有一个轴的张量对应数学上的*向量*（vector）；\n",
    "具有两个轴的张量对应数学上的*矩阵*（matrix）；\n",
    "具有两个轴以上的张量没有特殊的数学名称。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6bdaab0",
   "metadata": {
    "origin_pos": 10,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "首先，我们可以使用 `arange` 创建一个行向量 `x`。这个行向量包含以0开始的前12个整数，它们默认创建为整数。也可指定创建类型为浮点数。张量中的每个值都称为张量的 *元素*（element）。例如，张量 `x` 中有 12 个元素。除非额外指定，新的张量将存储在内存中，并采用基于CPU的计算。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b977093a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.542283Z",
     "iopub.status.busy": "2022-12-07T16:28:01.541755Z",
     "iopub.status.idle": "2022-12-07T16:28:01.553811Z",
     "shell.execute_reply": "2022-12-07T16:28:01.553055Z"
    },
    "origin_pos": 13,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.arange(12)\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f80f754",
   "metadata": {
    "origin_pos": 16
   },
   "source": [
    "[**可以通过张量的`shape`属性来访问张量（沿每个轴的长度）的*形状***]\n",
    "(~~和张量中元素的总数~~)。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b7e39a32",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.557389Z",
     "iopub.status.busy": "2022-12-07T16:28:01.556948Z",
     "iopub.status.idle": "2022-12-07T16:28:01.563199Z",
     "shell.execute_reply": "2022-12-07T16:28:01.562469Z"
    },
    "origin_pos": 17,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([12])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1029d98a",
   "metadata": {
    "origin_pos": 18
   },
   "source": [
    "如果只想知道张量中元素的总数，即形状的所有元素乘积，可以检查它的大小（size）。\n",
    "因为这里在处理的是一个向量，所以它的`shape`与它的`size`相同。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b6e3e2bd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.566826Z",
     "iopub.status.busy": "2022-12-07T16:28:01.566010Z",
     "iopub.status.idle": "2022-12-07T16:28:01.571319Z",
     "shell.execute_reply": "2022-12-07T16:28:01.570575Z"
    },
    "origin_pos": 20,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "12"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.numel()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e1b111a",
   "metadata": {
    "origin_pos": 23
   },
   "source": [
    "[**要想改变一个张量的形状而不改变元素数量和元素值，可以调用`reshape`函数。**]\n",
    "例如，可以把张量`x`从形状为（12,）的行向量转换为形状为（3,4）的矩阵。\n",
    "这个新的张量包含与转换前相同的值，但是它被看成一个3行4列的矩阵。\n",
    "要重点说明一下，虽然张量的形状发生了改变，但其元素值并没有变。\n",
    "注意，通过改变张量的形状，张量的大小不会改变。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "309722cd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.574981Z",
     "iopub.status.busy": "2022-12-07T16:28:01.574441Z",
     "iopub.status.idle": "2022-12-07T16:28:01.579697Z",
     "shell.execute_reply": "2022-12-07T16:28:01.579008Z"
    },
    "origin_pos": 24,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0,  1,  2,  3],\n",
       "        [ 4,  5,  6,  7],\n",
       "        [ 8,  9, 10, 11]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = x.reshape(3, 4)\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7377c5e1",
   "metadata": {
    "origin_pos": 27
   },
   "source": [
    "我们不需要通过手动指定每个维度来改变形状。\n",
    "也就是说，如果我们的目标形状是（高度,宽度），\n",
    "那么在知道宽度后，高度会被自动计算得出，不必我们自己做除法。\n",
    "在上面的例子中，为了获得一个3行的矩阵，我们手动指定了它有3行和4列。\n",
    "幸运的是，我们可以通过`-1`来调用此自动计算出维度的功能。\n",
    "即我们可以用`x.reshape(-1,4)`或`x.reshape(3,-1)`来取代`x.reshape(3,4)`。\n",
    "\n",
    "有时，我们希望[**使用全0、全1、其他常量，或者从特定分布中随机采样的数字**]来初始化矩阵。\n",
    "我们可以创建一个形状为（2,3,4）的张量，其中所有元素都设置为0。代码如下：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "833fe454",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.583460Z",
     "iopub.status.busy": "2022-12-07T16:28:01.582839Z",
     "iopub.status.idle": "2022-12-07T16:28:01.588562Z",
     "shell.execute_reply": "2022-12-07T16:28:01.587876Z"
    },
    "origin_pos": 29,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[0., 0., 0., 0.],\n",
       "         [0., 0., 0., 0.],\n",
       "         [0., 0., 0., 0.]],\n",
       "\n",
       "        [[0., 0., 0., 0.],\n",
       "         [0., 0., 0., 0.],\n",
       "         [0., 0., 0., 0.]]])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.zeros((2, 3, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61cc04dc",
   "metadata": {
    "origin_pos": 32
   },
   "source": [
    "同样，我们可以创建一个形状为`(2,3,4)`的张量，其中所有元素都设置为1。代码如下：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "40772601",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.592461Z",
     "iopub.status.busy": "2022-12-07T16:28:01.591857Z",
     "iopub.status.idle": "2022-12-07T16:28:01.597800Z",
     "shell.execute_reply": "2022-12-07T16:28:01.597100Z"
    },
    "origin_pos": 34,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[1., 1., 1., 1.],\n",
       "         [1., 1., 1., 1.],\n",
       "         [1., 1., 1., 1.]],\n",
       "\n",
       "        [[1., 1., 1., 1.],\n",
       "         [1., 1., 1., 1.],\n",
       "         [1., 1., 1., 1.]]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.ones((2, 3, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9a7bab5c",
   "metadata": {
    "origin_pos": 37
   },
   "source": [
    "有时我们想通过从某个特定的概率分布中随机采样来得到张量中每个元素的值。\n",
    "例如，当我们构造数组来作为神经网络中的参数时，我们通常会随机初始化参数的值。\n",
    "以下代码创建一个形状为（3,4）的张量。\n",
    "其中的每个元素都从均值为0、标准差为1的标准高斯分布（正态分布）中随机采样。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d4fcb962",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.601753Z",
     "iopub.status.busy": "2022-12-07T16:28:01.601160Z",
     "iopub.status.idle": "2022-12-07T16:28:01.606633Z",
     "shell.execute_reply": "2022-12-07T16:28:01.605931Z"
    },
    "origin_pos": 39,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.7277, -1.3848, -0.2607,  0.9701],\n",
       "        [-2.3290, -0.3754,  0.2457,  0.0760],\n",
       "        [-1.2832, -0.3600, -0.3321,  0.8184]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.randn(3, 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58a269e5",
   "metadata": {
    "origin_pos": 42
   },
   "source": [
    "我们还可以[**通过提供包含数值的Python列表（或嵌套列表），来为所需张量中的每个元素赋予确定值**]。\n",
    "在这里，最外层的列表对应于轴0，内层的列表对应于轴1。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "394e6a3a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.610117Z",
     "iopub.status.busy": "2022-12-07T16:28:01.609477Z",
     "iopub.status.idle": "2022-12-07T16:28:01.615388Z",
     "shell.execute_reply": "2022-12-07T16:28:01.614630Z"
    },
    "origin_pos": 44,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[2, 1, 4, 3],\n",
       "        [1, 2, 3, 4],\n",
       "        [4, 3, 2, 1]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "766cea1f",
   "metadata": {
    "origin_pos": 47
   },
   "source": [
    "## 运算符\n",
    "\n",
    "我们的兴趣不仅限于读取数据和写入数据。\n",
    "我们想在这些数据上执行数学运算，其中最简单且最有用的操作是*按元素*（elementwise）运算。\n",
    "它们将标准标量运算符应用于数组的每个元素。\n",
    "对于将两个数组作为输入的函数，按元素运算将二元运算符应用于两个数组中的每对位置对应的元素。\n",
    "我们可以基于任何从标量到标量的函数来创建按元素函数。\n",
    "\n",
    "在数学表示法中，我们将通过符号$f: \\mathbb{R} \\rightarrow \\mathbb{R}$\n",
    "来表示*一元*标量运算符（只接收一个输入）。\n",
    "这意味着该函数从任何实数（$\\mathbb{R}$）映射到另一个实数。\n",
    "同样，我们通过符号$f: \\mathbb{R}, \\mathbb{R} \\rightarrow \\mathbb{R}$\n",
    "表示*二元*标量运算符，这意味着该函数接收两个输入，并产生一个输出。\n",
    "给定同一形状的任意两个向量$\\mathbf{u}$和$\\mathbf{v}$和二元运算符$f$，\n",
    "我们可以得到向量$\\mathbf{c} = F(\\mathbf{u},\\mathbf{v})$。\n",
    "具体计算方法是$c_i \\gets f(u_i, v_i)$，\n",
    "其中$c_i$、$u_i$和$v_i$分别是向量$\\mathbf{c}$、$\\mathbf{u}$和$\\mathbf{v}$中的元素。\n",
    "在这里，我们通过将标量函数升级为按元素向量运算来生成向量值\n",
    "$F: \\mathbb{R}^d, \\mathbb{R}^d \\rightarrow \\mathbb{R}^d$。\n",
    "\n",
    "对于任意具有相同形状的张量，\n",
    "[**常见的标准算术运算符（`+`、`-`、`*`、`/`和`**`）都可以被升级为按元素运算**]。\n",
    "我们可以在同一形状的任意两个张量上调用按元素操作。\n",
    "在下面的例子中，我们使用逗号来表示一个具有5个元素的元组，其中每个元素都是按元素操作的结果。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "ccf751ee",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.619942Z",
     "iopub.status.busy": "2022-12-07T16:28:01.619317Z",
     "iopub.status.idle": "2022-12-07T16:28:01.627243Z",
     "shell.execute_reply": "2022-12-07T16:28:01.626521Z"
    },
    "origin_pos": 49,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([ 3.,  4.,  6., 10.]),\n",
       " tensor([-1.,  0.,  2.,  6.]),\n",
       " tensor([ 2.,  4.,  8., 16.]),\n",
       " tensor([0.5000, 1.0000, 2.0000, 4.0000]),\n",
       " tensor([ 1.,  4., 16., 64.]))"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.tensor([1.0, 2, 4, 8])\n",
    "y = torch.tensor([2, 2, 2, 2])\n",
    "x + y, x - y, x * y, x / y, x ** y  # **运算符是求幂运算"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "147e0960",
   "metadata": {
    "origin_pos": 52
   },
   "source": [
    "(**“按元素”方式可以应用更多的计算**)，包括像求幂这样的一元运算符。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "696900f7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.630779Z",
     "iopub.status.busy": "2022-12-07T16:28:01.630107Z",
     "iopub.status.idle": "2022-12-07T16:28:01.635477Z",
     "shell.execute_reply": "2022-12-07T16:28:01.634784Z"
    },
    "origin_pos": 54,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.exp(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc287989",
   "metadata": {
    "origin_pos": 57
   },
   "source": [
    "除了按元素计算外，我们还可以执行线性代数运算，包括向量点积和矩阵乘法。\n",
    "我们将在 :numref:`sec_linear-algebra`中解释线性代数的重点内容。\n",
    "\n",
    "[**我们也可以把多个张量*连结*（concatenate）在一起**]，\n",
    "把它们端对端地叠起来形成一个更大的张量。\n",
    "我们只需要提供张量列表，并给出沿哪个轴连结。\n",
    "下面的例子分别演示了当我们沿行（轴-0，形状的第一个元素）\n",
    "和按列（轴-1，形状的第二个元素）连结两个矩阵时，会发生什么情况。\n",
    "我们可以看到，第一个输出张量的轴-0长度（$6$）是两个输入张量轴-0长度的总和（$3 + 3$）；\n",
    "第二个输出张量的轴-1长度（$8$）是两个输入张量轴-1长度的总和（$4 + 4$）。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "cf38c887",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.639161Z",
     "iopub.status.busy": "2022-12-07T16:28:01.638398Z",
     "iopub.status.idle": "2022-12-07T16:28:01.646858Z",
     "shell.execute_reply": "2022-12-07T16:28:01.646135Z"
    },
    "origin_pos": 59,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([[ 0.,  1.,  2.,  3.],\n",
       "         [ 4.,  5.,  6.,  7.],\n",
       "         [ 8.,  9., 10., 11.],\n",
       "         [ 2.,  1.,  4.,  3.],\n",
       "         [ 1.,  2.,  3.,  4.],\n",
       "         [ 4.,  3.,  2.,  1.]]),\n",
       " tensor([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],\n",
       "         [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],\n",
       "         [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]]))"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.arange(12, dtype=torch.float32).reshape((3,4))\n",
    "Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])\n",
    "torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b511a4e2",
   "metadata": {
    "origin_pos": 62
   },
   "source": [
    "有时，我们想[**通过*逻辑运算符*构建二元张量**]。\n",
    "以`X == Y`为例：\n",
    "对于每个位置，如果`X`和`Y`在该位置相等，则新张量中相应项的值为1。\n",
    "这意味着逻辑语句`X == Y`在该位置处为真，否则该位置为0。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f760ca1d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.650566Z",
     "iopub.status.busy": "2022-12-07T16:28:01.649959Z",
     "iopub.status.idle": "2022-12-07T16:28:01.654963Z",
     "shell.execute_reply": "2022-12-07T16:28:01.654231Z"
    },
    "origin_pos": 63,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[False,  True, False,  True],\n",
       "        [False, False, False, False],\n",
       "        [False, False, False, False]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X == Y"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5287e1e",
   "metadata": {
    "origin_pos": 64
   },
   "source": [
    "[**对张量中的所有元素进行求和，会产生一个单元素张量。**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "7c176a4d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.658532Z",
     "iopub.status.busy": "2022-12-07T16:28:01.658029Z",
     "iopub.status.idle": "2022-12-07T16:28:01.663161Z",
     "shell.execute_reply": "2022-12-07T16:28:01.662413Z"
    },
    "origin_pos": 65,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(66.)"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X.sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff6e6c02",
   "metadata": {
    "origin_pos": 67
   },
   "source": [
    "## 广播机制\n",
    ":label:`subsec_broadcasting`\n",
    "\n",
    "在上面的部分中，我们看到了如何在相同形状的两个张量上执行按元素操作。\n",
    "在某些情况下，[**即使形状不同，我们仍然可以通过调用\n",
    "*广播机制*（broadcasting mechanism）来执行按元素操作**]。\n",
    "这种机制的工作方式如下：\n",
    "\n",
    "1. 通过适当复制元素来扩展一个或两个数组，以便在转换之后，两个张量具有相同的形状；\n",
    "2. 对生成的数组执行按元素操作。\n",
    "\n",
    "在大多数情况下，我们将沿着数组中长度为1的轴进行广播，如下例子：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "f1a78cda",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.666847Z",
     "iopub.status.busy": "2022-12-07T16:28:01.666215Z",
     "iopub.status.idle": "2022-12-07T16:28:01.671897Z",
     "shell.execute_reply": "2022-12-07T16:28:01.671182Z"
    },
    "origin_pos": 69,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([[0],\n",
       "         [1],\n",
       "         [2]]),\n",
       " tensor([[0, 1]]))"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = torch.arange(3).reshape((3, 1))\n",
    "b = torch.arange(2).reshape((1, 2))\n",
    "a, b"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ea719e1",
   "metadata": {
    "origin_pos": 72
   },
   "source": [
    "由于`a`和`b`分别是$3\\times1$和$1\\times2$矩阵，如果让它们相加，它们的形状不匹配。\n",
    "我们将两个矩阵*广播*为一个更大的$3\\times2$矩阵，如下所示：矩阵`a`将复制列，\n",
    "矩阵`b`将复制行，然后再按元素相加。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "9ea4c05a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.675382Z",
     "iopub.status.busy": "2022-12-07T16:28:01.674877Z",
     "iopub.status.idle": "2022-12-07T16:28:01.679881Z",
     "shell.execute_reply": "2022-12-07T16:28:01.679188Z"
    },
    "origin_pos": 73,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0, 1],\n",
       "        [1, 2],\n",
       "        [2, 3]])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a + b"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1c289ca",
   "metadata": {
    "origin_pos": 74
   },
   "source": [
    "## 索引和切片\n",
    "\n",
    "就像在任何其他Python数组中一样，张量中的元素可以通过索引访问。\n",
    "与任何Python数组一样：第一个元素的索引是0，最后一个元素索引是-1；\n",
    "可以指定范围以包含第一个元素和最后一个之前的元素。\n",
    "\n",
    "如下所示，我们[**可以用`[-1]`选择最后一个元素，可以用`[1:3]`选择第二个和第三个元素**]：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "f3aa99c2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.683181Z",
     "iopub.status.busy": "2022-12-07T16:28:01.682528Z",
     "iopub.status.idle": "2022-12-07T16:28:01.688248Z",
     "shell.execute_reply": "2022-12-07T16:28:01.687556Z"
    },
    "origin_pos": 75,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([ 8.,  9., 10., 11.]),\n",
       " tensor([[ 4.,  5.,  6.,  7.],\n",
       "         [ 8.,  9., 10., 11.]]))"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X[-1], X[1:3]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a47b41fd",
   "metadata": {
    "origin_pos": 76,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[**除读取外，我们还可以通过指定索引来将元素写入矩阵。**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c0a1c2d4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.691920Z",
     "iopub.status.busy": "2022-12-07T16:28:01.691320Z",
     "iopub.status.idle": "2022-12-07T16:28:01.696674Z",
     "shell.execute_reply": "2022-12-07T16:28:01.695981Z"
    },
    "origin_pos": 78,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.,  1.,  2.,  3.],\n",
       "        [ 4.,  5.,  9.,  7.],\n",
       "        [ 8.,  9., 10., 11.]])"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X[1, 2] = 9\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f43fa16c",
   "metadata": {
    "origin_pos": 80
   },
   "source": [
    "如果我们想[**为多个元素赋值相同的值，我们只需要索引所有元素，然后为它们赋值。**]\n",
    "例如，`[0:2, :]`访问第1行和第2行，其中“:”代表沿轴1（列）的所有元素。\n",
    "虽然我们讨论的是矩阵的索引，但这也适用于向量和超过2个维度的张量。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "da6dc5b4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.700265Z",
     "iopub.status.busy": "2022-12-07T16:28:01.699658Z",
     "iopub.status.idle": "2022-12-07T16:28:01.705050Z",
     "shell.execute_reply": "2022-12-07T16:28:01.704366Z"
    },
    "origin_pos": 81,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[12., 12., 12., 12.],\n",
       "        [12., 12., 12., 12.],\n",
       "        [ 8.,  9., 10., 11.]])"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X[0:2, :] = 12\n",
    "X"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1fea0db",
   "metadata": {
    "origin_pos": 83
   },
   "source": [
    "## 节省内存\n",
    "\n",
    "[**运行一些操作可能会导致为新结果分配内存**]。\n",
    "例如，如果我们用`Y = X + Y`，我们将取消引用`Y`指向的张量，而是指向新分配的内存处的张量。\n",
    "\n",
    "在下面的例子中，我们用Python的`id()`函数演示了这一点，\n",
    "它给我们提供了内存中引用对象的确切地址。\n",
    "运行`Y = Y + X`后，我们会发现`id(Y)`指向另一个位置。\n",
    "这是因为Python首先计算`Y + X`，为结果分配新的内存，然后使`Y`指向内存中的这个新位置。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "3539c38d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.708652Z",
     "iopub.status.busy": "2022-12-07T16:28:01.707936Z",
     "iopub.status.idle": "2022-12-07T16:28:01.713553Z",
     "shell.execute_reply": "2022-12-07T16:28:01.712859Z"
    },
    "origin_pos": 84,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "before = id(Y)\n",
    "Y = Y + X\n",
    "id(Y) == before"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60824ee7",
   "metadata": {
    "origin_pos": 85
   },
   "source": [
    "这可能是不可取的，原因有两个：\n",
    "\n",
    "1. 首先，我们不想总是不必要地分配内存。在机器学习中，我们可能有数百兆的参数，并且在一秒内多次更新所有参数。通常情况下，我们希望原地执行这些更新；\n",
    "2. 如果我们不原地更新，其他引用仍然会指向旧的内存位置，这样我们的某些代码可能会无意中引用旧的参数。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10603b2d",
   "metadata": {
    "origin_pos": 86,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "幸运的是，(**执行原地操作**)非常简单。\n",
    "我们可以使用切片表示法将操作的结果分配给先前分配的数组，例如`Y[:] = <expression>`。\n",
    "为了说明这一点，我们首先创建一个新的矩阵`Z`，其形状与另一个`Y`相同，\n",
    "使用`zeros_like`来分配一个全$0$的块。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "9800284e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.717333Z",
     "iopub.status.busy": "2022-12-07T16:28:01.716751Z",
     "iopub.status.idle": "2022-12-07T16:28:01.721658Z",
     "shell.execute_reply": "2022-12-07T16:28:01.720936Z"
    },
    "origin_pos": 89,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "id(Z): 139931132035296\n",
      "id(Z): 139931132035296\n"
     ]
    }
   ],
   "source": [
    "Z = torch.zeros_like(Y)\n",
    "print('id(Z):', id(Z))\n",
    "Z[:] = X + Y\n",
    "print('id(Z):', id(Z))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21d1867d",
   "metadata": {
    "origin_pos": 92,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[**如果在后续计算中没有重复使用`X`，\n",
    "我们也可以使用`X[:] = X + Y`或`X += Y`来减少操作的内存开销。**]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "118199c7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.725521Z",
     "iopub.status.busy": "2022-12-07T16:28:01.724748Z",
     "iopub.status.idle": "2022-12-07T16:28:01.730112Z",
     "shell.execute_reply": "2022-12-07T16:28:01.729349Z"
    },
    "origin_pos": 94,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "before = id(X)\n",
    "X += Y\n",
    "id(X) == before"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a52e90a0",
   "metadata": {
    "origin_pos": 96
   },
   "source": [
    "## 转换为其他Python对象\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "458d0cd9",
   "metadata": {
    "origin_pos": 98,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "将深度学习框架定义的张量[**转换为NumPy张量（`ndarray`）**]很容易，反之也同样容易。\n",
    "torch张量和numpy数组将共享它们的底层内存，就地操作更改一个张量也会同时更改另一个张量。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "4ae87f13",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.734214Z",
     "iopub.status.busy": "2022-12-07T16:28:01.733587Z",
     "iopub.status.idle": "2022-12-07T16:28:01.739355Z",
     "shell.execute_reply": "2022-12-07T16:28:01.738447Z"
    },
    "origin_pos": 100,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(numpy.ndarray, torch.Tensor)"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A = X.numpy()\n",
    "B = torch.tensor(A)\n",
    "type(A), type(B)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5a8be1e",
   "metadata": {
    "origin_pos": 103
   },
   "source": [
    "要(**将大小为1的张量转换为Python标量**)，我们可以调用`item`函数或Python的内置函数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "cf26d4aa",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T16:28:01.742894Z",
     "iopub.status.busy": "2022-12-07T16:28:01.742318Z",
     "iopub.status.idle": "2022-12-07T16:28:01.748354Z",
     "shell.execute_reply": "2022-12-07T16:28:01.747641Z"
    },
    "origin_pos": 105,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([3.5000]), 3.5, 3.5, 3)"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = torch.tensor([3.5])\n",
    "a, a.item(), float(a), int(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f3b7eb0",
   "metadata": {
    "origin_pos": 108
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 深度学习存储和操作数据的主要接口是张量（$n$维数组）。它提供了各种功能，包括基本数学运算、广播、索引、切片、内存节省和转换其他Python对象。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 运行本节中的代码。将本节中的条件语句`X == Y`更改为`X < Y`或`X > Y`，然后看看你可以得到什么样的张量。\n",
    "1. 用其他形状（例如三维张量）替换广播机制中按元素操作的两个张量。结果是否与预期相同？\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f41e8f8f",
   "metadata": {
    "origin_pos": 110,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/1747)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}